package com.mjk.common.core.rmq.mq;

import com.mjk.common.core.rmq.conf.RmqProperty;
import com.mjk.common.util.ObjectUtils;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;

/**
 * 
 * @author mjk
 * @date 2019年3月8日
 */
public class RmqChannel {
	private CachingConnectionFactory cachingConnectionFactory;
	private final RmqProperty rmqProperty;

	public RmqChannel(RmqProperty rmqProperty) {
		this.rmqProperty = rmqProperty;
	}

	public void connect() {
		cachingConnectionFactory = new CachingConnectionFactory();
		if (!ObjectUtils.isEmpty(rmqProperty.getHost())) {
			cachingConnectionFactory.setHost(rmqProperty.getHost());
		}
		if (!ObjectUtils.isEmpty(this.rmqProperty.getAddresses())) {
			cachingConnectionFactory.setAddresses(this.rmqProperty.getAddresses());
		}
		cachingConnectionFactory.setUsername(this.rmqProperty.getUserName());
		cachingConnectionFactory.setPassword(this.rmqProperty.getPassword());
		if (this.rmqProperty.getConnectionTimeout() > 0) {
			cachingConnectionFactory.setConnectionTimeout(this.rmqProperty.getConnectionTimeout());
		}
		if (this.rmqProperty.getHandshakeTimeout() > 0) {
			cachingConnectionFactory.getRabbitConnectionFactory()
					.setHandshakeTimeout(this.rmqProperty.getHandshakeTimeout());
		}
	}

	public void disConnect() {
		if (ObjectUtils.isNotEmpty(cachingConnectionFactory)) {
			cachingConnectionFactory.destroy();
		}
	}

	public CachingConnectionFactory getConnectionFactory() {
		return cachingConnectionFactory;
	}

	public RmqProperty getProperty() {
		return rmqProperty;
	}
}